<?php
/**
* 标签类
* @copyright 2013-1-21 
*/ 
class Tags{

	private $tag=null;

	private $articleId=0;

	private $tagToArticle=null;

	private $spell=null;

/**
* 初始化
* @access public
* @param int $id
*/
	public function __construct($id)
	{
		import('@.ORG.ChineseSpell');
		$this->articleId=$id;
		$this->tag=M('Tag');
		$this->tagToArticle=M('TagArticle');
		$this->spell=new ChineseSpell();
	}

/**
* 新增标签
* @access public
* @param array $arr 新增标签数组
*/
	public function add($arr)
	{
		$this->delFromTagArticle();
		foreach($arr as $v)
		{
			if($v!='')
			{
				$oldData=$this->have($v);
				if(empty($oldData))
				{
					$data['title']=$v;
					$data['code']=$this->spell->getFullSpell(iconv('utf-8','gbk',$v),'');
					$newTagId=$this->tag->data($data)->add();
					$this->addToTagArticle($newTagId);
				}else
					{
						$this->addToTagArticle($oldData['id']);
					}
			}
		}
	}

/**
* 判断标签唯一性
* @access private
* @param string $str 标签名
* @return array 
*/
	private function have($str)
	{
		$where['title']=$str;
		$where['code']=$this->spell->getFullSpell(iconv('utf-8','gbk',$str),'');
		$where['_logic']='OR';
		return $this->tag->field('id')->where($where)->find();
	}

/**
* 插入关联数据到tag_article表
* @access private
* @param int $id 新标签ID
*/
	private function addToTagArticle($id)
	{
		$old=$this->tagToArticle->field('id')->where(array('value_id'=>$this->articleId,'tag_id'=>$id))->find();
		if(empty($old))
		{
			$data['value_id']=$this->articleId;
			$data['tag_id']=$id;
			$this->tagToArticle->data($data)->add();
		}
	}

/**
* 删除指定信息ID关联数据
* @access private
*/	
	private function delFromTagArticle()
	{
		@$this->tagToArticle->where(array('value_id'=>$this->articleId))->delete();
	}

/**
* 删除指定信息ID集合关联数据
* @access public
* @param string $id ID字符串如:1,2,3
*/
	public static function delFromTagArticleByValueId($id)
	{
		$where['value_id']=array('in',$id);
		M('TagArticle')->where($where)->delete();
	}

/**
* 删除指定标签ID集合关联数据
* @access public
* @param string $id ID字符串如:1,2,3
*/
	public static function delFromTagArticleByTagId($id)
	{
		$where['tag_id']=array('in',$id);
		M('TagArticle')->where($where)->delete();
	}	

/**
 * 根据指定信息ID获取标签信息
 * @access public
 * @param int $id 信息ID
 * @return array
 */
	public static function getTagByArticleId($id)
	{
		return M('TagArticle')->field('title')->join('LEFT JOIN '.C('DB_PREFIX')
.'tag tag ON tag.id = '.C('DB_PREFIX').'tag_article.tag_id')->where('value_id = '.$id)->select();
	}


}
?>